/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
export const doCustomTimes = (times: number, callback: any) => {
  let i = -1
  while (++i < times) {
    callback(i)
  }
}

export const localSave = (key: string, value: string) => {
  localStorage.setItem(key, value)
}

export const localRead = (key: string) => {
  return localStorage.getItem(key) || ''
}

export const localRemove = (key: string) => {
  localStorage.removeItem(key)
}

export const fontSize = (res: number) => {
  const clientWidth =
    window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  if (!clientWidth) return
  const fontSize = 100 * (clientWidth / 1920)
  return res * fontSize
}

/**
 * @description 验证手机号
 * @param phone
 * @returns boolean
 */
export const validatePhone = (phone: string) => {
  const reg = /^1[3456789]\d{9}$/
  return reg.test(phone)
}

/**
 * @description 验证密码格式
 * @param password
 * @returns boolean
 */
export const validatePassword = (password: string) => {
  const reg = /((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))(?!^.*[\u4E00-\u9FA5].*$)^\S{6,20}$/
  return reg.test(password)
}
// scrollTop animation
export const scrollTop = (el: any, from = 0, to: number, duration = 500, endCallback: any) => {
  if (!window.requestAnimationFrame) {
    window.requestAnimationFrame =
      window.webkitRequestAnimationFrame ||
      (window as any).mozRequestAnimationFrame ||
      (window as any).msRequestAnimationFrame ||
      function(callback) {
        return window.setTimeout(callback, 1000 / 60)
      }
  }
  const difference = Math.abs(from - to)
  const step = Math.ceil((difference / duration) * 50)

  const scroll = (start: number, end: number, step: number) => {
    if (start === end) {
      endCallback && endCallback()
      return
    }

    let d = start + step > end ? end : start + step
    if (start > end) {
      d = start - step < end ? end : start - step
    }

    if (el === window) {
      window.scrollTo(d, d)
    } else {
      el.scrollTop = d
    }
    window.requestAnimationFrame(() => scroll(d, end, step))
  }
  scroll(from, to, step)
}
